package com.huluspace.apicall.service;

import com.huluspace.apicall.dto.WeatherResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;

@Service
public class WeatherService {
  @Value("${weather.api.key}")
  private String apiKey;

  // 构造器方式注入WebClient
  private final WebClient webClient;
  public WeatherService(WebClient webClient) {
    this.webClient = webClient;
  }

  public WeatherResponse getWeatherByCity(String location) {
    return webClient.get()
        .uri(uriBuilder -> uriBuilder
            .queryParam("location", location)
            .build()) // 构建请求地址（uri）
        .header("X-QW-Api-Key", apiKey) // 在请求头中设置API-KEY
        .retrieve() // 表示发送请求并准备获取响应
        .bodyToMono(WeatherResponse.class) // 将响应体反序列化为WeatherResponse对象
        .block(); // 同步方式返回，等待请求完成并返回具体数据
  }
}

